#ifndef LIBCO_MONITOR_H
#define LIBCO_MONITOR_H

#include "sys/epoll.h"
#include <string.h>
#include <cstdint>
#include "processor.hpp"
#include "thread.hpp"
#include "macro.h"
#include "coroutine.hpp"
#include "timer.hpp"
#include "concurrent.hpp"
#include "epollevent.hpp"
#include "hook.hpp"

namespace libco {

/// 线程本地调度器
extern thread_local Processor *t_proc;
extern thread_local uint64_t t_id;
/// 线程本地任务队列
static thread_local TaskQueue *t_local_q;

constexpr uint8_t COMAXPROCS{4};

class Monitor : Noncopyable, public TimerManager, public EpollManager {
private:
    /// 运行monitor的线程
    Thread* m_root_thread;
    Thread* m_threads[COMAXPROCS];
    Processor* m_procs[COMAXPROCS];
    int m_pipe_fd[COMAXPROCS][2];
    std::atomic<size_t> m_active_procs;
    bool m_stop = false;

private:
    void run_proc(Processor*);
    
public:
    // typedef std::shared_ptr<Monitor> ptr;

    Monitor();
    ~Monitor();

    /// 信号处理函数
    static void exit_sig_handler(int);
    static void run();
    static void schedule(Coroutine::ptr);
    static void schedule(std::function<void()>);
    static bool stopping();
    static Monitor* GetThis();
    static TaskQueue* GetGlobalQue();
};

} // namespace libco


#endif